package com.theydream.qeechain.ARcaught;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.Vector;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.hardware.Camera;
import android.hardware.Camera.PictureCallback;
import android.hardware.Camera.ShutterCallback;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.util.Log;
import android.view.Display;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.FrameLayout;

import com.theydream.qeechain.battle.Battle;
import com.theydream.qeechain.globaldata.GlobalData;
import com.theydream.qeechain.libs.FourSqareVenue;
import com.theydream.qeechain.libs.FourSquareClient;

public class ARClick extends Activity implements OnClickListener {
	/** Called when the activity is first created. */
	CustomCameraView cv;
	public static volatile Context ctx;
	int numOfPet = 0;
	ARLayout ar;
	volatile Location curLocation = null;
	ArrayList<Integer> petDegree = new ArrayList<Integer>();
	private Context mContext = this;

	private LocationListener gpsListener = new LocationListener() {

		public void onLocationChanged(Location location) {
			Log.e("HoldMe", "Got first");
			if (curLocation != null)
				return;
			curLocation = location;
			new Thread() {
				public void run() {
					FourSquareClient fc = new FourSquareClient();
					Vector<FourSqareVenue> vc = fc.getVenuList(curLocation);
					Log.e("Where4",
							"CurLocation LA:" + curLocation.getLatitude()
									+ " LO:" + curLocation.getLongitude());
					ar.clearARViews();
					if (vc != null && vc.size() > 0) {
						Enumeration<FourSqareVenue> e = vc.elements();
						while (e.hasMoreElements()) {
							FourSqareVenue fq = (FourSqareVenue) e
									.nextElement();
							Log.e("Where4", "Got Venue:" + fq.name);
							if (fq.location != null)
								Log.i("Where4",
										"Lat:" + fq.location.getLatitude()
												+ ":"
												+ fq.location.getLongitude());
							Log.e("Where4", "Azimuth: " + fq.azimuth);
							ar.addARView(fq);
						}
					}
				}
			}.start();
			LocationManager locMan = (LocationManager) ctx
					.getSystemService(Context.LOCATION_SERVICE);
			locMan.removeUpdates(this);

		}

		public void onProviderDisabled(String provider) {
		}

		public void onProviderEnabled(String provider) {
		}

		public void onStatusChanged(String provider, int status, Bundle extras) {
		}

	};

	private void addLoadingLayouts() {
		FourSqareVenue fs;
		for (int i = 0; i < 1; i++) {
			fs = new FourSqareVenue(this.getApplicationContext());
			int degree = (int) ((Math.random() * 350) + 10);
			// int inclination = (int) ((Math.random() * 30) + 1);
			int inclination = 0;

			if (numOfPet > 0)
				for (int i1 = 0; i1 < petDegree.size(); i1++)
					if (Math.abs(degree - petDegree.get(i1)) < 20)
						degree += 20;

			petDegree.add(degree);
			GlobalData.getInstance().setPetDegree(degree);
			fs.azimuth = degree;
			fs.inclination = inclination;
			fs.name = "a";
			ar.addARView(fs);
			numOfPet++;
		}
	}

	public void onStart() {
		super.onStart();
	}

	public void onCreate(Bundle savedInstanceState) {
		try {
			super.onCreate(savedInstanceState);

			GlobalData.getInstance().setArID(
					RandomEncounterLogic.getNextEncounter().getId());
			ctx = this.getApplicationContext();
			setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
			requestWindowFeature(Window.FEATURE_NO_TITLE);

			getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
					WindowManager.LayoutParams.FLAG_FULLSCREEN);

			ar = new ARLayout(getApplicationContext());

			cv = new CustomCameraView(this.getApplicationContext());
			requestWindowFeature(Window.FEATURE_NO_TITLE);
			// cl = new CompassListener(this.getApplicationContext());
			WindowManager w = getWindowManager();
			Display d = w.getDefaultDisplay();
			int width = d.getWidth();
			int height = d.getHeight();
			ar.screenHeight = height;
			ar.screenWidth = width;
			FrameLayout rl = new FrameLayout(getApplicationContext());
			rl.addView(cv, width, height);
			ar.debug = true;
			rl.addView(ar, width, height);

			// ARLayout temp =new ARLayout(this);

			ar.setOnClickListener(this);

			setContentView(rl);
			LocationManager locMan = (LocationManager) ctx
					.getSystemService(Context.LOCATION_SERVICE);
			locMan.requestLocationUpdates(LocationManager.GPS_PROVIDER, 100, 1,
					gpsListener);
			// rl.bringChildToFront(cl);
			addLoadingLayouts();

		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void onStop() {
		super.onStop();
		this.finish();
	}

	
	 public void onResume() {
	 super.onResume();
	 
	 
	 }

	public void onDestroy() {
		super.onDestroy();
		cv.closeCamera();
		ar.close();
	}

	// Catch view
	public void onClick(View v) {
		// TODO Auto-generated method stub
		// Toast.makeText(this, "Don't touch me.", Toast.LENGTH_SHORT).show();
		for (int i = 0; i < petDegree.size(); i++)
			if (ar.direction < petDegree.get(i) + 20
					&& ar.direction > petDegree.get(i) - 20) {

				cv.camera.takePicture(shutterCallback, rawPictureCallback,
						jpegPictureCallback);

				// Intent to dialog activity
				// Intent toDialog = new Intent(ARClick.this, ARDialog.class);
				// startActivity(toDialog);
				// this.finish();
				Intent intent = new Intent(this, Battle.class);
				Bundle bundle = new Bundle();
				bundle.putString("eid", GlobalData.getInstance().getArID());
				intent.putExtras(bundle);
				startActivity(intent);
				this.finish();
			}

	}

	ShutterCallback shutterCallback = new ShutterCallback() {
		@Override
		public void onShutter() {
		}
	};
	PictureCallback rawPictureCallback = new PictureCallback() {

		@Override
		public void onPictureTaken(byte[] arg0, Camera arg1) {

		}
	};
	PictureCallback jpegPictureCallback = new PictureCallback() {

		@Override
		public void onPictureTaken(byte[] arg0, Camera arg1) {
			Bitmap bitmapPicture = BitmapFactory.decodeByteArray(arg0, 0,
					arg0.length);
			StoreByteImage(mContext, bitmapPicture, 50, "ImageName");

		}
	};

	public static boolean StoreByteImage(Context mContext, Bitmap imageData,
			int quality, String expName) {

		File sdImageMainDirectory = new File("/sdcard");
		FileOutputStream fileOutputStream = null;
		try {

			BitmapFactory.Options options = new BitmapFactory.Options();
			options.inSampleSize = 5;

			// Bitmap myImage = BitmapFactory.decodeByteArray(imageData, 0,
			// imageData.length, options);

			fileOutputStream = new FileOutputStream(
					sdImageMainDirectory.toString() + "/image.jpg");

			BufferedOutputStream bos = new BufferedOutputStream(
					fileOutputStream);

			imageData.compress(CompressFormat.JPEG, quality, bos);

			bos.flush();
			bos.close();

		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return true;
	}
}